package com.example.shuqishixi;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;
import java.util.Random;

@WebServlet(name = "regservlet", value = "/regservlet")
public class regservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 获取表单数据
        String name = request.getParameter("txtname");
        String pwd = request.getParameter("txtpwd");
        String sex = request.getParameter("sex");
        String email = request.getParameter("txtemail");
        String role = request.getParameter("user_role");

        // 生成随机手机号
        String phone = generateRandomPhone();

        // 处理性别为空的情况
        if (sex == null) {
            sex = "1";
        }

        // 默认身份为普通用户
        if (role == null || role.isEmpty()) {
            role = "user";
        }

        Connection conn = null;
        PreparedStatement ps = null;

        try {
            // 使用新版 MySQL JDBC 驱动类名
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
            String dbUser = "root";
            String dbPassword = "123456";
            conn = DriverManager.getConnection(url, dbUser, dbPassword);

            // 检查用户是否已存在
            if (userExists(conn, name)) {
                response.getWriter().println("用户名已存在");
                return;
            }

            // 使用 PreparedStatement 插入数据，防止 SQL 注入
            String sql = "INSERT INTO users (username, password, sex, email, user_role, phone) VALUES (?, ?, ?, ?, ?, ?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setString(2, pwd);
            ps.setString(3, sex);
            ps.setString(4, email);
            ps.setString(5, role);
            ps.setString(6, phone);

            int ret = ps.executeUpdate();

            if (ret == 1) {
                // 注册成功，跳转到登录页面
                response.sendRedirect("index.jsp");
            } else {
                response.getWriter().println("注册失败，请重试");
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            response.getWriter().println("找不到数据库驱动");
        } catch (SQLException ex) {
            ex.printStackTrace();
            response.getWriter().println("数据库连接失败：" + ex.getMessage());
        } finally {
            // 关闭资源
            try {
                if (ps != null) ps.close();
                if (conn != null) conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    // 生成随机手机号
    private String generateRandomPhone() {
        Random random = new Random();
        StringBuilder phone = new StringBuilder("1");
        // 手机号第二位通常为3-9
        phone.append(random.nextInt(7) + 3);
        // 剩余9位随机数字
        for (int i = 0; i < 9; i++) {
            phone.append(random.nextInt(10));
        }
        return phone.toString();
    }

    // 检查用户是否已存在
    private boolean userExists(Connection conn, String username) throws SQLException {
        String sql = "SELECT username FROM users WHERE username = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, username);
            try (ResultSet rs = ps.executeQuery()) {
                return rs.next();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
